package uk.gov.swmprobation.cplitebase;

import uk.gov.swmprobation.cplitebase.R;
import android.accounts.AccountManager;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.android.gms.common.AccountPicker;

@SuppressWarnings("deprecation")
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	
	final static public String submitHintTitle = "Hint - Send project";
	final static public String submitHintMessage = "Slide the map to target the location of photo then click on the tick to send.\n\nTo cancel click on the cross.";
	final static public int submitHintIcon = R.drawable.tick;
	final static public String startHintTitle = "Hint - Start";
	final static public String startHintMessage = "Tap the camera icon in the top right to start suggesting a project.";
	final static public int startHintIcon = android.R.drawable.ic_menu_camera;
	
	final static public int REQUEST_CODE = 1;
	SharedPreferences sharedPref;
	
	Preference emailPreference;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPref = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
        
        addPreferencesFromResource(R.xml.preferences);
        
        emailPreference = (Preference) findPreference("email");
        String accountName = sharedPref.getString("user_email", "No email selected");
        emailPreference.setSummary(accountName);

        Preference prefWaitWifi = (Preference)findPreference("pref_wait_wifi");
        int wifiCode = Integer.parseInt(sharedPref.getString("pref_wait_wifi", "2"));
        prefWaitWifi.setSummary(wifiText(wifiCode));
        
        Preference prefResetHints = (Preference)findPreference("resetHints");
        prefResetHints.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference preference) {
				sharedPref.edit().putBoolean(submitHintTitle, true).commit();
				sharedPref.edit().putBoolean(startHintTitle, true).commit();
				sharedPref.edit().putBoolean(CreateProject.thankYouTitle, true).commit();
				Toast.makeText(SettingsActivity.this, "All Hints will be shown", Toast.LENGTH_SHORT).show();
				return false;
			}
        	
        });

        emailPreference.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference preference) {
				try {
			        Intent intent = AccountPicker.newChooseAccountIntent(null, null,
			        		new String[] { "com.google", "com.android.email", "com.outlook.Z7.eas"}, false, null, null, null, null);
			        startActivityForResult(intent, REQUEST_CODE);
			    } catch (ActivityNotFoundException e) {
			        // TODO
			    }
				return false;
			}
        	
        });
        
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.settings, menu);
		return true;
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
		int itemID = item.getItemId();
        if (itemID == R.id.menu_about) {
			startActivity(new Intent(this,About.class));
			return true;
		} else if (itemID == R.id.menu_privacy) {
			startActivity(new Intent(this,Privacy.class));
			return true;
		} else {
			return super.onOptionsItemSelected(item);
		}
    }
	
	@Override
	protected void onResume() {
	    super.onResume();
	    // Set up a listener whenever a key changes
	    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onPause() {
	    super.onPause();
	    // Unregister the listener whenever a key changes
	    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
	}
    
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPref,	String key) {
		if (key.equals("pref_user_code")) {
            Preference connectionPref = findPreference(key);
            connectionPref.setSummary(sharedPref.getString(key, "General Public"));
        }
		if (key.equals("pref_wait_wifi")) {
            Preference connectionPref = findPreference(key);
            int wifiCode = Integer.parseInt(sharedPref.getString("pref_wait_wifi", "2"));
            connectionPref.setSummary(wifiText(wifiCode));
        }
		
	}
	
	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
	    if (requestCode == SettingsActivity.REQUEST_CODE){
	    	EasyTracker easyTracker = EasyTracker.getInstance(this);
		    if (resultCode == RESULT_OK) {
		        String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
		        sharedPref.edit().putString("user_email", accountName).commit();
		        emailPreference.setSummary(accountName);
		        easyTracker.send(MapBuilder
		    		      .createEvent("user_action",     // Event category (required)
		    		                   "email_entry",  // Event action (required)
		    		                   "entered",   // Event label
		    		                   null)            // Event value
		    		      .build()
		    		  );
		    } else {
		    	easyTracker.send(MapBuilder
		    		      .createEvent("user_action",     // Event category (required)
		    		                   "email_entry",  // Event action (required)
		    		                   "not_entered",   // Event label
		    		                   null)            // Event value
		    		      .build()
		    		  );
		    }
		}
	}
	
	public static String wifiText(int wifiCode){

		switch (wifiCode){
			case 1:
				return "Only send when Wifi available";
			case 2:
				return "Ask me when Wifi not available";
			case 3:
				return "Send straight away";
			default:
				return "Ask me when Wifi not available";
		}	
	}	
}
